package com.itheima.controller;


/*
 *   抽取一个基本serlet  使用uri提取方法名
 * */

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.service.store.*;
import com.itheima.service.store.impl.*;
import com.itheima.service.system.DeptService;
import com.itheima.service.system.UserService;
import com.itheima.service.system.impl.DeptServiceImpl;
import com.itheima.service.system.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

//@WebServlet("/user/*")
public class BaseServlet extends HttpServlet {

    //业务层对象
    public CatalogService catalogService;
    public CourseService courseService;
    public QuestionItemService questionItemService;
    public CompanyService companyService;
    public QuestionService questionService;
    public UserService userService;
    public DeptService deptService;
    //json工具对象
    public static ObjectMapper mapper;

    @Override
    public void init() throws ServletException {
        //创建Json转换对象
        mapper = new ObjectMapper();
        //各个业务层对象
        catalogService = new CatalogServiceImpl();
        courseService = new CourseServiceImpl();
        questionItemService = new QuestionItemServiceImpl();
        companyService= new CompanyServiceImpl();
        questionService = new QuestionServiceImpl();
        userService = new UserServiceImpl();
        deptService= new DeptServiceImpl();
    }

    //使用反射抽取方法名
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取统一资源标识符
        String uri = req.getRequestURI();
        //抽取方法名
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);

        try {
            //获取方法对象
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //因为是私有方法 需要暴力反射
            method.setAccessible(true);
            //调用方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
